package gotnames.dm;

import gotnames.Utils;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Blob;
import com.medallia.tiny.Func;

/**
 * A profile picture belonging to a {@link User}. See {@link ProfilePictureData}.
 */
@PersistenceCapable
public class ProfilePicture {
	
	@PrimaryKey
	private Long userKey;
	
	@Persistent
	private String md5;
	
	@Persistent
	private Blob picture;

	/** @return the primary key of the user this picture belongs to */
	public Long getUserKey() {
		return userKey;
	}

	public void setUserKey(Long userKey) {
		this.userKey = userKey;
	}

	/** @return the MD5 of the picture data itself */
	public String getMd5() {
		return md5;
	}

	public void setMd5(String md5) {
		this.md5 = md5;
	}

	/** @return the picture data itself */
	public Blob getPicture() {
		return picture;
	}

	public void setPicture(Blob picture) {
		this.picture = picture;
	}
	
	/**
	 * Save the given profile picture data for the given user; if a
	 * {@link ProfilePicture} object already exists it is updated.
	 * 
	 * @return the MD5 of the profile picture data
	 */
	public static String saveProfilePicture(User user, PersistenceManager pm, ProfilePictureData profilePicture) {
		if (profilePicture == null)
			return null;
		
		final Long userKey = user.getKey();
		final byte[] profilePictureBytes = profilePicture.image;
		final String profilePictureMd5 = profilePicture.md5;
		
		new UpdateOrCreate<ProfilePicture>(pm, ProfilePicture.class) {
			@Override protected Object execute(Query query) {
				query.setFilter("userKey == " + Utils.notNull(userKey, "Key cannot be null"));
				return query.execute();
			}
			@Override protected void setValues(ProfilePicture pp) {
				pp.setUserKey(userKey);
				pp.setMd5(profilePictureMd5);
				pp.setPicture(new Blob(profilePictureBytes));
			}
		}.go();
		
		return profilePictureMd5;
	}

	/** {@link Func} which calls {@link ProfilePicture#getUserKey()} */
	public static final Func<ProfilePicture, Long> USER_KEY_FUNC = new Func<ProfilePicture, Long>() {
		@Override public Long call(ProfilePicture pp) {
			return pp.getUserKey();
		}
	};

}
